<?php

class functions{
    private $dado;
    private $current;
    private $list = array();


    public function post_isset($value){

            if(isset($_POST["$value"])){

                $this->dado = $_POST["$value"];

                return $this;
           }
            else{
            $this->dado = NULL;
            echo $this->dado;
            return $this;
        }
    }

    public function get_isset($value){

        if(isset($_GET["$value"])){

            $this->dado = $_GET["$value"];
            return $this;
        }
        else{
            $value = NULL;
            
            $this->dado = $value;
            
            return $this;
        }
    }
    
    public function files_isset($value){

            if(isset($_FILES["$value"])){

                $this->dado = $_FILES["$value"];

                
                return $this;
           }
            else{
            $this->dado = NULL;
            echo $this->dado;
            return $this;
        }
    }

    public function get_value($value){
        if(isset($value)){
            $this->dado = $value;

            return $this;
        }
        else{
            $value = NULL;
            
            $this->dado = $value;
            
            return $this;
        }
    }
    
    public function request_value($value){
       $vlr = isset($_REQUEST["$value"])? $_REQUEST["$value"] : "";

       return $vlr;
    }

    public function anti_sql_injection() {
        if (!is_numeric($this->dado)) {
              $this->dado = get_magic_quotes_gpc() ? stripslashes($this->dado) : $this->dado;
              $this->dado = function_exists('mysql_real_escape_string') ? mysql_real_escape_string($this->dado) : mysql_escape_string($this->dado);
        }
           return $this;
    }

    public function only_num(){
            $this->dado = preg_replace( '#[^0-9]#', '',"$this->dado");
            return $this;
    }

    public function only_name(){
            $this->dado = preg_replace('#[^a-zA-Z]#','',"$this->dado");
            return $this;
    }

    public function toupper(){
            $this->dado =  strtoupper("$this->dado");
            return $this;
    }

    public function lower(){

            $this->dado = strtolower("$this->dado");
            return $this;
    }

    public function format ($mask, $form=""){
	$output = preg_replace("[' '-./( ) t]", '', $this->dado);
	$size = (strlen($output) -2);

        switch($mask){
            case 'nit'  : $this->dado = '9.999.999.999-9';    break; //nit
            case 'cpf'  : $this->dado = '999.999.999-99' ;    break; //cpf
            case 'nb'   : $this->dado = '999.999.999-9';      break; //nb
            case 'cnpj' : $this->dado = '99.999.999/9999-99'; break; //cnpj
            case 'phone': $this->dado = '(99) 9999-9999';     break; //fone
            case 'cep'  : $this->dado = '99.999-999' ;        break; //cep
            case 'date' : $this->dado = '99/99/9999' ;        break; //data
            case 'ol'   : $this->dado = '99.999.999' ;        break; //ol
            case 'br'   : $this->dado = 'R$ '.number_format($this->dado, 2, ',', '.'); return $this; break;  // retorna R$100.000,50
            case 'us'   : $this->dado = 'US$ '.number_format($this->dado, 2, ',', '.'); return $this; break;  // retorna R$100.000,50
            case 'form' : $this->dado = $form;                break; // qualque forma
        }

	$index = -1;
	for ($i=0; $i < strlen($this->dado); $i++)
		if ($this->dado[$i]=='9') $this->dado[$i] = $output[++$index];

	return $this;
}

    public function desformat($mask = NULL){
            if($mask == NULL)
                $this->dado = preg_replace( '#[^0-9]#', '',"$this->dado");
            else{
                switch($mask){
                    case 'br'   :   $this->dado = str_replace(',','.',str_replace('.','',substr($this->dado,2))); break;
                    case 'us'   :   $this->dado = str_replace(',','.',str_replace('.','',substr($this->dado,3))); break;
                }
            }
            return $this;
    }

    public function filterInt($value){
        $value = filter_var($value,FILTER_VALIDATE_INT);
        $value = (int) $value;
        return $value;
    }
    
    public function img($dir,$width,$atualiz="") {
        $permission = array('image/jpg','image/jpeg','image/pjpeg','image/gif','image/png','image/bmp');
        $img = $this->dado;
        
        $tmp = $img['tmp_name'];
        $name = $img['name'];
        $type = $img['type'];
        
        if($type =='image/gif')
            $ext = '.gif';
        else if($type=='image/bmp')
            $ext = '.bmp';
        else if($type=='image/png')
            $ext = '.png';
        else
            $ext = '.jpg';
        
        if(!empty ($name) && in_array($type, $permission)){
            if(empty($atualiz))
                $name = 'i-academy-'.md5(uniqid(rand(),true)).$ext;
            else
                $name = $atualiz;
            
            $this->upload($tmp, $name, $width, $dir, $type);
        }
        
        $this->dado = $name;
        
               
        return $this;
    }
    
    
    private function upload($tmp, $name, $width, $dir, $type) {

        if($type =='image/gif')
            $image = imagecreatefromgif($tmp);
        else if($type=='image/bmp')
            $image = imagecreatefromwbmp($tmp);
        else if($type=='image/png')
            $image = imagecreatefrompng($tmp);
        else
            $image = imagecreatefromjpeg($tmp);

        
        $x = imagesx($image);
        $y = imagesy($image);
        $height = ($width*$y) / $x;
        
        $new = imagecreatetruecolor($width, $height);
        imagecopyresampled($new, $image, 0, 0, 0, 0, $width, $height, $x, $y);
        
        if($type =='image/gif')        
            imagegif($new, $dir.$name);
        else if($type=='image/bmp')
            imagewbmp($new, $dir.$name);
        else if($type=='image/png')
            imagepng($new, $dir.$name);
        else
            imagejpeg($new, $dir.$name);
        
        
        imagedestroy($new);
        imagedestroy($image);
        
        return $name;
        
    }
    
    public function deleteUploaded($arquivo) {
        if (!unlink($arquivo)){
            echo ("Erro ao deletar $arquivo");
  
        }
        else{
            echo ("Deletado $arquivo com sucesso!");
        }        
    }

    public function get(){
        if(is_array($this->dado))
            return $this->dado;
        else
            return trim($this->dado);
    }
    
        /*************[ FUNCOES para data ]************/

    /**
     * Função para converter data
     *
     * @return object
     * @example
     * <pre>
     *<?php
     *
     *   $data = "08/07/2009";
     *   echo date_convert($data);
     *
     *         saida: 2009-07-08
     *
     * </pre>
     */
    public function to_mysql_date(){

            $dd = substr($this->dado, 0,2);
            $mm = substr($this->dado, 3,2);
            $aa = substr($this->dado, 6,4);
            $time = substr($this->dado, 11,8);
            if($time != "")
                $this->dado = $aa."-".$mm."-".$dd." ".$time;
            else
                $this->dado = $aa."-".$mm."-".$dd;

            
        if($this->dado=='//' || $this->dado == '--')
        {
            $this->dado = '';
        }
        return $this;
    }

    public function to_php_date($format){
        $this->dado = date($format,strtotime($this->dado));

        if($this->dado=='01/01/1970')
        {
            $this->dado = '';
        }

        return $this;
    }

   /**
    *   Função para somar datas em dias
    *    Data no formato Y-m-d
    */
    public function dt_Somar($dias) {
        $data = str_replace("-","",$this->dado);
        $ano = substr ( $this->dado, 0, 4 );
        $mes = substr ( $this->dado, 4, 2 );
        $dia = substr ( $this->dado, 6, 2 );
        $novaData = mktime ( 0, 0, 0, $mes, $dia + $dias, $ano );
        return strftime("%Y-%m-%d", $novaData);
    }

   /**
    *   Função para somar datas em dias
    *    Data no formato Y-m-d
    */
    public function dt_Subtrair($dias) {
        $data = str_replace("-","",$this->dado);
        $ano = substr ( $this->dado, 0, 4 );
        $mes = substr ( $this->dado, 4, 2 );
        $dia = substr ( $this->dado, 6, 2 );
        $novaData = mktime ( 0, 0, 0, $mes, $dia - $dias, $ano );
        return strftime("%Y-%m-%d", $novaData);
    }

 /**
 * Calcula o intervalo entre duas datas no formato ISO, o intervalo é dado
 * no formato específicado em intevalor q pode ser
 * y - ano
 * m - meses
 * d - dias
 * h - horas
 * n - minutos
 * default ´segundos
 *
 * @param string $data1
 * @param string $data2
 * @param string $intervalo m, d, h, n,y
 * @return int|string intervalo de horas
 */
public function dataDif($data1, $data2, $intervalo) {

    switch ($intervalo) {
        case 'y':
            $Q = 86400*365;
            break; //ano
        case 'm':
            $Q = 2592000;
            break; //mes
        case 'd':
            $Q = 86400;
            break; //dia
        case 'h':
            $Q = 3600;
            break; //hora
        case 'n':
            $Q = 60;
            break; //minuto
        default:
            $Q = 1;
            break; //segundo
    }

    return round((strtotime($data2) - strtotime($data1)) / $Q);
}

       /**
    *   Função para somar datas em dias
    *    Data no formato Y-m-d
    */
    public function dtSomar($data,$dias) {
        $data = str_replace("-","",$data);
        $ano = substr ( $data, 0, 4 );
        $mes = substr ( $data, 4, 2 );
        $dia = substr ( $data, 6, 2 );
        $novaData = mktime ( 0, 0, 0, $mes, $dia + $dias, $ano );
        return strftime("%Y-%m-%d", $novaData);
    }

    /*
     *   Função para subtrair datas em dias
     *   Data no formato Y-m-d
     */
    public function dtSubtrair($data,$dias) {
        $data = str_replace("-","",$data);
        $ano = substr ( $data, 0, 4 );
        $mes = substr ( $data, 4, 2 );
        $dia = substr ( $data, 6, 2 );
        $novaData = mktime ( 0, 0, 0, $mes, $dia - $dias, $ano );
        return strftime("%Y-%m-%d", $novaData);
   }

   public function go($location){
        header('Location:'.$location);
        print("<script>location.href='$location';</script>");
   }


    public function error(){
        echo '
              <div style="border: 1px solid #ff0000; padding: 5px 10px; background: #ffb8b8;">
                    Erro! Não foi possível recuperar os dados da pagina anterior. Tente novamente.
             </div>';
        echo '<script language="javascript">  window.setTimeout("history.go(-1)", 2500); </script> ';
    }

    /*************[ FUNCOES IMPRESSÃO ]************/

    public function text_limit($texto, $limite){

        $texto = substr($texto, 0, strrpos(substr($texto, 0, $limite), ' ')) . '...';

        return $texto;
    }

    public function spaces($tam){
        for($i = 0; $i< $tam; ++$i)
            echo "&nbsp ";
    }

    public function field_select($dados, $id, $default="", $size="",$class=""){
        echo '<select id="'.$id.'" name="'.$id.'" style="width: '.$size.'px;" class="'.$class.';" >';
        echo   "<option value=\"\">$default</option>";
        foreach($dados as $vlr){
             echo "<option value=\"$vlr\" id=\"$vlr\">$vlr</option>";
        }
        echo "</select>";
    }
    
    /**
     * Subistitui o Hidden("Location: ...") 
     */
    public function send_hide($form_name, $action, $array_hide){

       echo '<script type="text/javascript">',
                'window.onload = function(){',
                    'document.getElementById("submit").click();',
                 '}',
            '</script>';

      echo '<form name="'.$form_name.' " action= " '.$action.' " method="POST" enctype="multipart/form-data">';

      foreach($array_hide as $key => $value){
        echo      '<input type="hidden" id=" '.$key.'" name='."$key ".' value=" '.$value.' " />';
      }
        echo      '<input type="submit" id="submit" value="button_send" style="display: none;" />',
           "</form>";
    }
    
    public function send_button($form_name, $action, $name_button, $field_sendding, $value_sendding){
      echo '<form name="'.$form_name.' " action= "'.$action.'" method="POST" enctype="multipart/form-data">';
        echo      '<input type="hidden" id=" '.$field_sendding.'" name='."$field_sendding ".' value=" '.$value_sendding.' " />';
        echo      '<input type="submit" value="'.$name_button.'" />',
           "</form>";
    }

    public function send_hideimg($form_name, $action, $array_hide, $src_img,$alt_img, $class_img=""){

      echo '<form name="'.$form_name.'" action= "'.$action.'" method="POST" enctype="multipart/form-data">';

      foreach($array_hide as $key => $value){
        echo      '<input type="hidden" id="'.$key.'" name='."$key ".' value="'.$value.'" />';
      }
        echo      '<input type="image" value="submit" id="send" name="send" src="'.$src_img.'" alt="'.$alt_img.'" class="'.$class_img.'"/>',
           "</form>";
    }



    public function menu_table($page,$current,$_id=''){
       
        $this->current = $current;
       
          foreach($page as $name => $pag){

              $corrente = 'id=""';
              $vlrId = '';
              if(!empty($_id)) $_vlrId = $_id;

              if($name == $this->current){
                      $corrente = 'id="current"';
                      $pag = '#';
                      $this->list[] = '<li '.$corrente.'><a href="'.$pag.'"><span>'.$name.'</span></a></li>';
              }
              else
                $this->list[] = '<li '.$corrente.'><a href="'.$pag.'&id='.$_vlrId.'"><span>'.$name.'</span></a></li>';
       }
    }

    public function menu_print(){
        echo '<div id="tabs">',
                 '<ul>';

                 foreach($this->list as $value){
                     echo $value;
                 }

        echo   '</ul>',
        '</div>';
    }


    function encrypt($string){
        $string1 = sha1($string);

        $str_reverse = strrev($string);
        $str_reverse = sha1($str_reverse);

        $full_str = $string1.$str_reverse;

        return $full_str;
    }


}
?>
